import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { ListService, PagedResultDto } from '@abp/ng.core';
import { ThemeSharedModule } from '@abp/ng.theme.shared';
import { GongyingService } from './gongying.service';
import { GongyingDto, CreateUpdateGongyingDto } from './models';
import { ConfirmationService, Confirmation } from '@abp/ng.theme.shared';
import { ToasterService } from '@abp/ng.theme.shared';
import { Subscription } from 'rxjs';
import { finalize } from 'rxjs/operators';
import { ExcelExportService } from '../shared/services/excel-export.service';

@Component({
  selector: 'app-gongyings',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule, ThemeSharedModule],
  templateUrl: './gongyings.component.html',
  styleUrl: './gongyings.component.scss',
  providers: [ListService]
})
export class GongyingsComponent implements OnInit, OnDestroy {
  gongying = { items: [], totalCount: 0 } as PagedResultDto<GongyingDto>;
  createGongyingForm: FormGroup;
  isModalOpen = false;
  isEditMode = false;
  selectedGongyingId: string;
  isSaving = false;
  Math = Math; // 添加Math对象以在模板中使用
  
  // 复选框相关变量
  selectedItems: string[] = []; // 存储选中项ID
  isAllSelected = false; // 全选标记
  
  // 企业属性选项
  enterpriseAttributeOptions: string[] = [
    '国有企业',
    '民营企业',
    '外资企业',
    '合资企业',
    '上市公司',
    '私营企业',
    '个体工商户',
    '事业单位',
    '政府机构',
    '非盈利组织',
    '其他'
  ];
  
  // 分页相关变量
  pageSizeOptions = [10, 20, 30, 50];
  currentPageSize = 10;
  maxPageCount = 1; // 最大页数
  visiblePageNumbers: number[] = []; // 可见页码数组
  inputPageNumber: number = 1; // 输入的页码
  
  // 订阅对象
  private subscription: Subscription = new Subscription();
  
  // 添加搜索关键字属性
  nameKeyword = '';
  isSearchMode = false;
  
  // 添加加载状态
  isLoading = false;
  
  // 添加导出状态
  isExporting = false;
  
  constructor(
    public readonly list: ListService,
    private gongyingService: GongyingService,
    private fb: FormBuilder,
    private confirmation: ConfirmationService,
    private toaster: ToasterService,
    private excelExportService: ExcelExportService
  ) {
    this.createGongyingForm = this.fb.group({
      fullName: ['', [Validators.required, Validators.maxLength(100)]],
      address: [''],
      phone: ['', Validators.maxLength(20)],
      remarks: [''],
      enterpriseAttribute: ['', Validators.maxLength(50)],
      mainContact: ['', Validators.maxLength(50)],
      mobile: ['', Validators.maxLength(20)],
      emailAddress: ['', [Validators.maxLength(100), Validators.email]]
    });
  }

  ngOnInit() {
    // 初始化时确保页码是1
    this.list.page = 1;
    this.loadData();
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

  // 加载数据并处理分页
  loadData() {
    // 确保页面在有效范围内
    if (this.list.page <= 0) {
      this.list.page = 1;
    }
    
    // 设置加载状态
    this.isLoading = true;
    
    const streamCreator = (query) => {
      // 使用普通列表方法
      const params = {
        ...query,
        maxResultCount: this.currentPageSize,
        skipCount: (this.list.page - 1) * this.currentPageSize
      };
      
      // 根据是否在搜索模式选择不同的API
      if (this.isSearchMode && this.nameKeyword.trim()) {
        return this.gongyingService.searchByName(this.nameKeyword, params);
      } else {
        return this.gongyingService.getList(params);
      }
    };
    
    this.subscription.add(
      this.list.hookToQuery(streamCreator)
        .pipe(
          finalize(() => {
            this.isLoading = false; // 请求结束后，无论成功还是失败，都重置加载状态
            this.selectedItems = []; // 清空选中项
            this.isAllSelected = false; // 重置全选状态
          })
        )
        .subscribe(
          (response: PagedResultDto<GongyingDto>) => {
            this.gongying = response;
            // 计算最大页数
            if (response.totalCount > 0) {
              this.maxPageCount = Math.ceil(response.totalCount / this.currentPageSize);
              
              // 如果当前页超出最大页数，则返回到最后一页
              if (this.list.page > this.maxPageCount) {
                this.list.page = this.maxPageCount;
                // 重新加载正确的页数据，但不要造成无限循环
                if (response.items.length === 0) {
                  this.loadDataWithoutCheck();
                }
              }
            } else {
              this.maxPageCount = 1;
              this.list.page = 1;
            }
            
            // 更新页码显示
            this.updateVisiblePageNumbers();
          },
          error => {
            console.error('加载数据失败', error);
            let errorMessage = '加载数据失败，请稍后重试';
            if (error && error.error && error.error.message) {
              errorMessage = `${errorMessage}: ${error.error.message}`;
            }
            this.toaster.error(errorMessage, '错误', { life: 7000 });
          }
        )
    );
  }
  
  // 不进行页码检查的数据加载方法，避免循环
  loadDataWithoutCheck() {
    // 设置加载状态
    this.isLoading = true;
    
    const streamCreator = (query) => {
      // 使用普通列表方法
      const params = {
        ...query,
        maxResultCount: this.currentPageSize,
        skipCount: (this.list.page - 1) * this.currentPageSize
      };
      
      // 根据是否在搜索模式选择不同的API
      if (this.isSearchMode && this.nameKeyword.trim()) {
        return this.gongyingService.searchByName(this.nameKeyword, params);
      } else {
        return this.gongyingService.getList(params);
      }
    };
    
    this.subscription.add(
      this.list.hookToQuery(streamCreator)
        .pipe(
          finalize(() => {
            this.isLoading = false;
          })
        )
        .subscribe(
          (response: PagedResultDto<GongyingDto>) => {
            this.gongying = response;
            this.updateVisiblePageNumbers();
          },
          error => {
            console.error('加载数据失败', error);
            this.toaster.error('加载数据失败，请稍后重试', '错误');
          }
        )
    );
  }
  
  // 更新可见页码
  updateVisiblePageNumbers() {
    const totalPages = this.maxPageCount;
    const currentPage = this.list.page;
    const maxVisiblePages = 5; // 最多显示的页码数
    
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
    
    if (endPage - startPage + 1 < maxVisiblePages) {
      startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }
    
    this.visiblePageNumbers = [];
    
    // 添加首页附近的页码
    if (startPage > 1) {
      this.visiblePageNumbers.push(1);
      if (startPage > 2) {
        this.visiblePageNumbers.push(-1); // 省略号
      }
    }
    
    // 添加中间页码
    for (let i = startPage; i <= endPage; i++) {
      this.visiblePageNumbers.push(i);
    }
    
    // 添加尾页附近的页码
    if (endPage < totalPages) {
      if (endPage < totalPages - 1) {
        this.visiblePageNumbers.push(-1); // 省略号
      }
      this.visiblePageNumbers.push(totalPages);
    }
    
    // 更新输入框中的页码
    this.inputPageNumber = currentPage;
  }
  
  // 每页显示数量变化时的处理
  onPageSizeChange(pageSize: number) {
    this.currentPageSize = pageSize;
    this.list.page = 1; // 重置到第一页
    this.loadData();
  }
  
  // 跳转到指定页
  goToPage(page: number) {
    if (page < 1 || page > this.maxPageCount || page === this.list.page) {
      return;
    }
    this.list.page = page;
    this.loadData();
  }
  
  // 处理页码输入框的变化
  onPageInputChange(event: Event) {
    const input = event.target as HTMLInputElement;
    let value = parseInt(input.value, 10);
    
    if (isNaN(value)) {
      value = 1;
    } else if (value < 1) {
      value = 1;
    } else if (value > this.maxPageCount) {
      value = this.maxPageCount;
    }
    
    this.inputPageNumber = value;
  }
  
  // 处理页码输入框的按键事件
  onPageInputKeyUp(event: KeyboardEvent) {
    if (event.key === 'Enter') {
      this.goToPage(this.inputPageNumber);
    }
  }
  
  // 打开创建供应商模态框
  openCreateModal() {
    this.isModalOpen = true;
    this.isEditMode = false;
    this.createGongyingForm.reset();
    
    // 设置默认值
    this.createGongyingForm.patchValue({
      fullName: '',
      address: '',
      phone: '',
      remarks: '',
      enterpriseAttribute: '',
      mainContact: '',
      mobile: '',
      emailAddress: ''
    });
  }
  
  // 打开编辑供应商模态框
  openEditModal(gongyingId: string) {
    this.isModalOpen = true;
    this.isEditMode = true;
    this.selectedGongyingId = gongyingId;
    
    // 加载供应商数据
    this.gongyingService.getById(gongyingId).subscribe(
      (gongyingData) => {
        this.createGongyingForm.patchValue({
          fullName: gongyingData.fullName,
          address: gongyingData.address,
          phone: gongyingData.phone,
          remarks: gongyingData.remarks,
          enterpriseAttribute: gongyingData.enterpriseAttribute,
          mainContact: gongyingData.mainContact,
          mobile: gongyingData.mobile,
          emailAddress: gongyingData.emailAddress
        });
      },
      (error) => {
        this.toaster.error('加载供应商信息失败', '错误');
        console.error('加载供应商信息失败', error);
        this.closeModal();
      }
    );
  }
  
  // 关闭模态框
  closeModal() {
    this.isModalOpen = false;
    this.createGongyingForm.reset();
    // 在重置后设置默认空值，避免错误
    this.createGongyingForm.patchValue({
      fullName: '',
      address: '',
      phone: '',
      remarks: '',
      enterpriseAttribute: '',
      mainContact: '',
      mobile: '',
      emailAddress: ''
    }, {emitEvent: false});
  }
  
  // 保存供应商数据
  save() {
    if (this.createGongyingForm.invalid) {
      // 标记所有控件为已触摸，显示验证错误
      Object.keys(this.createGongyingForm.controls).forEach(key => {
        const control = this.createGongyingForm.get(key);
        control.markAsTouched();
      });
      return;
    }
    
    this.isSaving = true;
    
    const gongyingData = this.createGongyingForm.value as CreateUpdateGongyingDto;
    
    if (this.isEditMode) {
      // 编辑模式
      this.gongyingService.update(this.selectedGongyingId, gongyingData)
        .pipe(finalize(() => this.isSaving = false))
        .subscribe(
          () => {
            this.toaster.success('供应商信息已更新', '成功');
            this.closeModal();
            this.loadData();
          },
          error => {
            console.error('更新供应商失败', error);
            this.toaster.error('更新供应商失败，请稍后重试', '错误');
          }
        );
    } else {
      // 创建模式
      this.gongyingService.create(gongyingData)
        .pipe(finalize(() => this.isSaving = false))
        .subscribe(
          () => {
            this.toaster.success('供应商已创建', '成功');
            this.closeModal();
            this.loadData();
          },
          error => {
            console.error('创建供应商失败', error);
            this.toaster.error('创建供应商失败，请稍后重试', '错误');
          }
        );
    }
  }
  
  // 删除供应商
  deleteGongying(gongyingId: string) {
    this.confirmation.warn(
      '删除确认',
      '您确定要删除此供应商吗？',
      { messageLocalizationParams: [] }
    ).subscribe((status) => {
      if (status === Confirmation.Status.confirm) {
        this.gongyingService.delete(gongyingId).subscribe(
          () => {
            this.toaster.success('供应商已删除', '成功');
            this.loadData();
          },
          error => {
            console.error('删除供应商失败', error);
            this.toaster.error('删除供应商失败，请稍后重试', '错误');
          }
        );
      }
    });
  }
  
  // 搜索供应商
  searchGongying() {
    this.isSearchMode = !!this.nameKeyword.trim();
    this.list.page = 1; // 重置到第一页
    this.loadData();
  }
  
  // 重置搜索
  resetSearch() {
    this.nameKeyword = '';
    this.isSearchMode = false;
    this.list.page = 1; // 重置到第一页
    this.loadData();
  }
  
  // 导出选中项
  async exportSelectedItems() {
    if (this.selectedItems.length === 0) {
      this.toaster.warn('请先选择要导出的项', '提示');
      return;
    }
    
    this.isExporting = true;
    
    try {
      // 获取选中的供应商数据
      const selectedGongyings = this.gongying.items.filter(item => 
        this.selectedItems.includes(item.id)
      );
      
      // 导出为Excel
      await this.excelExportService.exportToExcel(
        selectedGongyings,
        '供应商列表_选中项',
        [
          { header: '供应商编码', key: 'supplierCode', width: 32 },
          { header: '供应商名称', key: 'fullName', width: 30 },
          { header: '联系人', key: 'mainContact', width: 15 },
          { header: '电话', key: 'phone', width: 15 },
          { header: '手机', key: 'mobile', width: 15 },
          { header: '地址', key: 'address', width: 40 },
          { header: '企业属性', key: 'enterpriseAttribute', width: 15 },
          { header: '备注', key: 'remarks', width: 30 }
        ]
      );
      
      this.toaster.success('导出成功', '成功');
    } catch (error) {
      console.error('导出失败', error);
      this.toaster.error('导出失败，请稍后重试', '错误');
    } finally {
      this.isExporting = false;
    }
  }
  
  // 导出当前页
  async exportCurrentPage() {
    if (this.gongying.items.length === 0) {
      this.toaster.warn('当前页没有数据可导出', '提示');
      return;
    }
    
    this.isExporting = true;
    
    try {
      // 导出为Excel
      await this.excelExportService.exportToExcel(
        this.gongying.items,
        '供应商列表_当前页',
        [
          { header: '供应商编码', key: 'supplierCode', width: 32 },
          { header: '供应商名称', key: 'fullName', width: 30 },
          { header: '联系人', key: 'mainContact', width: 15 },
          { header: '电话', key: 'phone', width: 15 },
          { header: '手机', key: 'mobile', width: 15 },
          { header: '地址', key: 'address', width: 40 },
          { header: '企业属性', key: 'enterpriseAttribute', width: 15 },
          { header: '备注', key: 'remarks', width: 30 }
        ]
      );
      
      this.toaster.success('导出成功', '成功');
    } catch (error) {
      console.error('导出失败', error);
      this.toaster.error('导出失败，请稍后重试', '错误');
    } finally {
      this.isExporting = false;
    }
  }
  
  // 导出全部数据
  exportAllData() {
    this.isExporting = true;
    
    // 定义获取所有数据的函数
    const fetchAllData = () => {
      return new Promise<GongyingDto[]>((resolve, reject) => {
        // 使用一个较大的页面大小获取所有数据
        const pageSize = 1000;
        let currentPage = 0;
        let allItems: GongyingDto[] = [];
        let totalCount = 0;
        
        const fetchPage = () => {
          this.gongyingService.getList({
            maxResultCount: pageSize,
            skipCount: currentPage * pageSize,
            sorting: ''
          }).subscribe(
            (result) => {
              allItems = [...allItems, ...result.items];
              totalCount = result.totalCount;
              
              if (allItems.length < totalCount) {
                currentPage++;
                fetchPage();
              } else {
                resolve(allItems);
              }
            },
            (error) => {
              reject(error);
            }
          );
        };
        
        fetchPage();
      });
    };
    
    // 执行导出
    fetchAllData()
      .then(async (allItems) => {
        try {
          // 导出为Excel
          await this.excelExportService.exportToExcel(
            allItems,
            '供应商列表_全部',
            [
              { header: '供应商编码', key: 'supplierCode', width: 32 },
              { header: '供应商名称', key: 'fullName', width: 30 },
              { header: '联系人', key: 'mainContact', width: 15 },
              { header: '电话', key: 'phone', width: 15 },
              { header: '手机', key: 'mobile', width: 15 },
              { header: '地址', key: 'address', width: 40 },
              { header: '企业属性', key: 'enterpriseAttribute', width: 15 },
              { header: '备注', key: 'remarks', width: 30 }
            ]
          );
          
          this.toaster.success('导出成功', '成功');
        } catch (error) {
          console.error('导出失败', error);
          this.toaster.error('导出失败，请稍后重试', '错误');
        }
      })
      .catch((error) => {
        console.error('获取数据失败', error);
        this.toaster.error('获取数据失败，请稍后重试', '错误');
      })
      .finally(() => {
        this.isExporting = false;
      });
  }
  
  // 全选/取消全选
  selectAll(checked: boolean): void {
    this.isAllSelected = checked;
    if (checked) {
      this.selectedItems = this.gongying.items.map(item => item.id);
    } else {
      this.selectedItems = [];
    }
  }
  
  // 切换单个项的选择状态
  toggleItemSelection(id: string): void {
    const index = this.selectedItems.indexOf(id);
    if (index === -1) {
      this.selectedItems.push(id);
    } else {
      this.selectedItems.splice(index, 1);
    }
    
    // 更新全选状态
    this.isAllSelected = this.gongying.items.length > 0 && 
      this.selectedItems.length === this.gongying.items.length;
  }
  
  // 批量删除
  deleteSelected(): void {
    if (this.selectedItems.length === 0) {
      this.toaster.warn('请先选择要删除的项', '提示');
      return;
    }
    
    this.confirmation.warn(
      '批量删除确认',
      `您确定要删除选中的 ${this.selectedItems.length} 个供应商吗？`,
      { messageLocalizationParams: [] }
    ).subscribe((status) => {
      if (status === Confirmation.Status.confirm) {
        // 逐个删除选中的项
        const deletePromises = this.selectedItems.map(id => 
          this.gongyingService.delete(id).toPromise()
        );
        
        Promise.all(deletePromises)
          .then(() => {
            this.toaster.success(`成功删除 ${this.selectedItems.length} 个供应商`, '成功');
            this.selectedItems = [];
            this.isAllSelected = false;
            this.loadData();
          })
          .catch(error => {
            console.error('批量删除失败', error);
            this.toaster.error('批量删除失败，请稍后重试', '错误');
          });
      }
    });
  }
} 